package com.northwind.controller;

import com.northwind.entity.Admin;
import com.northwind.service.AdminService;
import com.northwind.util.ImageCodeUtil;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;

@Controller
@RequestMapping("admin")
public class AdminController {
    @Resource
    AdminService adminService;

    @RequestMapping("getImageCode")
    public void getImageCode(HttpSession session, HttpServletResponse response){
        //获取验证码随机字符
        String imageCode = ImageCodeUtil.getSecurityCode();
        System.out.println("随机验证码为:"+imageCode);
        //SecurityUtils.getSubject().getSession().setAttribute("imageCode",imageCode);
        session.setAttribute("imageCode",imageCode);
        //session.setAttribute("test","test");
        System.out.println("session中的为:"+(String)session.getAttribute("imageCode"));

       /* String imageCode1 = (String) session.getAttribute("imageCode");
        System.out.println("session里为:"+imageCode1);*/

        BufferedImage image = ImageCodeUtil.createImage(imageCode);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image,"png",outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("验证码输出错误");
        }
    }

    @ResponseBody
    @RequestMapping("login")
    public HashMap<String, Object> login(Admin admin, String enCode,HttpSession session){

        return adminService.loginShiro(admin, enCode);
    }


    @RequestMapping("logout")
    public String logout(HttpSession session){
        session.removeAttribute("admin");
        return "redirect:/login/login.jsp";
    }
}
